<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据分析</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/moment@2.29.4/moment.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #0066cc;
            --secondary-color: #00ccff;
            --dark-bg: #0a1929;
            --card-bg: #0f2942;
            --text-color: #e0f0ff;
            --accent-color: #00ffcc;
            --danger-color: #ff3366;
            --warning-color: #ffcc00;
            --success-color: #33cc33;
            --border-radius: 10px;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Roboto', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--text-color);
            background-color: var(--dark-bg);
            padding: 20px;
            overflow-x: hidden;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(0, 204, 255, 0.2);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo-icon {
            font-size: 24px;
            color: var(--accent-color);
        }

        .logo-text {
            font-weight: 700;
            font-size: 18px;
            color: var(--accent-color);
        }

        .user-controls {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .notification-icon, .user-profile {
            position: relative;
            cursor: pointer;
        }

        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background-color: var(--danger-color);
            color: white;
            font-size: 10px;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .dashboard {
            display: grid;
            grid-template-columns: 250px 1fr;
            grid-gap: 20px;
            flex: 1;
            overflow: hidden;
        }

        .sidebar {
            display: flex;
            flex-direction: column;
            background-color: var(--card-bg);
            border-radius: var(--border-radius);
            overflow-y: auto;
            flex: 0 0 250px;
            max-height: calc(100vh - 120px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .main-content {
            display: flex;
            flex-direction: column;
            overflow-y: auto;
            max-height: calc(100vh - 120px);
        }

        .card {
            background-color: var(--card-bg);
            border-radius: var(--border-radius);
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            border: 1px solid rgba(0, 204, 255, 0.1);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            flex: 1;
        }

        .card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            font-weight: 600;
            color: var(--accent-color);
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(0, 198, 255, 0.2);
        }

        .card-content {
            font-size: 14px;
        }

        .btn {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            margin-top: 5px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn:hover {
            box-shadow: 0 0 15px rgba(0, 204, 255, 0.5);
            transform: translateY(-2px);
        }

        .btn i {
            font-size: 16px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th, .table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid rgba(0, 204, 255, 0.2);
        }

        .table th {
            color: var(--accent-color);
            background-color: rgba(0, 0, 0, 0.2);
        }

        .table tr:hover {
            background-color: rgba(0, 198, 255, 0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-size: 14px;
            color: var(--accent-color);
        }

        input, select, textarea {
            width: 100%;
            padding: 10px;
            background-color: rgba(0, 0, 0, 0.3);
            border: 1px solid var(--primary-color);
            border-radius: 5px;
            color: var(--text-color);
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: var(--accent-color);
        }

        .chart-container {
            height: 300px;
            margin-bottom: 20px;
            position: relative;
        }

        .status-badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
        }

        .status-active {
            background-color: rgba(51, 204, 51, 0.2);
            color: var(--success-color);
        }

        .status-inactive {
            background-color: rgba(255, 204, 0, 0.2);
            color: var(--warning-color);
        }

        .nav-item {
            margin-bottom: 10px;
            padding: 12px 15px;
            border-radius: 7px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .nav-item:hover, .nav-item.active {
            background-color: rgba(0, 198, 255, 0.2);
            color: var(--accent-color);
        }

        .nav-item i {
            font-size: 16px;
            width: 20px;
            text-align: center;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }

        .pagination button {
            background-color: rgba(0, 0, 0, 0.2);
            color: var(--text-color);
            border: 1px solid rgba(0, 204, 255, 0.3);
            padding: 8px 15px;
            margin: 0 5px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .pagination button:hover, .pagination button.active {
            background-color: rgba(0, 198, 255, 0.3);
        }

        .refresh-icon {
            cursor: pointer;
            color: var(--accent-color);
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.1);
            }
            100% {
                transform: scale(1);
            }
        }

        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(10, 25, 41, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            flex-direction: column;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid rgba(0, 204, 255, 0.3);
            border-radius: 50%;
            border-top-color: var(--accent-color);
            animation: spin 1s ease-in-out infinite;
            margin-bottom: 20px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .loading-text {
            color: var(--text-color);
            font-size: 16px;
        }

        @media (max-width: 768px) {
            .dashboard {
                grid-template-columns: 1fr;
            }

            .sidebar {
                grid-column: 1 / -1;
                margin-bottom: 20px;
            }
        }

        .filter-row {
            display: flex;
            justify-content: space-between;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .filter-group {
            flex: 1;
            min-width: 200px;
        }

        .responsive-table {
            overflow-x: auto;
        }

        .last-updated {
            font-size: 12px;
            color: rgba(224, 240, 255, 0.7);
            margin-top: 5px;
            text-align: right;
        }
    </style>
</head>
<body>
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
        <div class="loading-text">加载中，请稍候...</div>
    </div>

    <header>
        <div class="logo">
            <div class="logo-icon"><i class="fas fa-chart-line"></i></div>
            <div class="logo-text">高级风险评估系统</div>
        </div>
        <div class="user-controls">
            <div class="notification-icon">
                <i class="fas fa-bell"></i>
                <span class="notification-badge">3</span>
            </div>
            <div class="user-profile">
                <i class="fas fa-user-circle"></i>
                <span style="margin-left: 5px;">管理员</span>
            </div>
        </div>
    </header>

    <div class="dashboard">
        <div class="sidebar">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-server"></i> 系统统计
                </div>
                <div class="card-content">
                    <p>总评估次数: <span class="total-assessments">2,548</span></p>
                    <p>高风险企业: <span class="high-risk-companies">328</span></p>
                    <p>今日新增评估: <span class="today-assessments">42</span></p>
                    <p>系统状态:
                        <span class="status-badge status-active" id="systemStatus">正常运行</span>
                    </p>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fas fa-cog"></i> 系统设置
                </div>
                <div class="card-content">
                    <div class="nav-item" id="riskConfigNav">
                        <i class="fas fa-cog"></i> <a href="风险参数分析.html" class="case-link">风险参数配置</a>
                    </div>
                    <div class="nav-item active">
                        <i class="fas fa-chart-bar"></i> 数据分析
                    </div>
                    <div class="nav-item" id="userManagerNav">
                        <i class="fas fa-user-cog"></i> <a href="用户管理.html"class="case-link">用户管理</a>
                    </div>
                </div>
            </div>
        </div>

        <div class="main-content">
            <div class="card">
                <div class="card-header">
                    <i class="fas fa-chart-line"></i> 风险评估概览
                </div>
                <div class="card-content">
                    <div class="filter-row">
                        <div class="filter-group">
                            <label for="dateRange">日期范围</label>
                            <select id="dateRange">
                                <option value="7">最近7天</option>
                                <option value="30" selected>最近30天</option>
                                <option value="90">最近90天</option>
                                <option value="365">最近一年</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label for="riskType">风险类型</label>
                            <select id="riskType">
                                <option value="all" selected>所有类型</option>
                                <option value="financial">财务风险</option>
                                <option value="market">市场风险</option>
                                <option value="management">管理风险</option>
                                <option value="external">外部风险</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label for="industry">行业</label>
                            <select id="industry">
                                <option value="all" selected>所有行业</option>
                                <option value="tech">科技</option>
                                <option value="finance">金融</option>
                                <option value="manufacturing">制造业</option>
                                <option value="retail">零售业</option>
                                <option value="service">服务业</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label>&nbsp;</label>
                            <button class="btn" id="refreshDataBtn">
                                <i class="fas fa-sync-alt"></i> 刷新数据
                            </button>
                        </div>
                    </div>

                    <div class="chart-container">
                        <canvas id="assessmentTrendChart"></canvas>
                        <div class="last-updated" id="trendLastUpdated">最后更新: 刚刚</div>
                    </div>

                    <div class="chart-container">
                        <canvas id="riskDistributionChart"></canvas>
                        <div class="last-updated" id="distributionLastUpdated">最后更新: 刚刚</div>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fas fa-users"></i> 用户行为分析
                </div>
                <div class="card-content">
                    <div class="chart-container">
                        <canvas id="userActivityChart"></canvas>
                        <div class="last-updated" id="activityLastUpdated">最后更新: 刚刚</div>
                    </div>

                    <div class="responsive-table">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>用户</th>
                                    <th>角色</th>
                                    <th>评估次数</th>
                                    <th>平均评分</th>
                                    <th>最后登录</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="userActivityTableBody">
                                <!-- 用户行为数据将通过JavaScript动态生成 -->
                            </tbody>
                        </table>
                    </div>

                     <div class="pagination" id="userActivityPagination">
                        <!-- 用户行为表格分页按钮将通过JavaScript动态生成 -->
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fas fa-map-marked-alt"></i> 风险分布热力图
                </div>
                <div class="card-content">
                    <div class="chart-container" style="height: 400px;">
                        <div id="riskHeatmap" style="width: 100%; height: 100%;"></div>
                        <div class="last-updated" style="position: absolute; bottom: 10px; right: 10px;" id="heatmapLastUpdated">最后更新: 刚刚</div>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fas fa-chart-pie"></i> 风险趋势预测
                </div>
                <div class="card-content">
                    <div class="chart-container">
                        <canvas id="riskPredictionChart"></canvas>
                        <div class="last-updated" id="predictionLastUpdated">最后更新: 刚刚</div>
                    </div>

                    <div style="display: flex; justify-content: space-between; margin-top: 20px;">
                        <div style="flex: 1; padding: 10px; background-color: rgba(0, 0, 0, 0.2); border-radius: 5px; margin-right: 10px;">
                            <h3 style="color: var(--accent-color); margin-bottom: 10px; font-size: 16px;">高风险行业</h3>
                            <p>制造业: <span class="industry-percentage">28%</span></p>
                            <p>零售业: <span class="industry-percentage">22%</span></p>
                            <p>服务业: <span class="industry-percentage">19%</span></p>
                            <p>科技业: <span class="industry-percentage">15%</span></p>
                        </div>
                        <div style="flex: 1; padding: 10px; background-color: rgba(0, 0, 0, 0.2); border-radius: 5px;">
                            <h3 style="color: var(--accent-color); margin-bottom: 10px; font-size: 16px;">风险类别分析</h3>
                            <p>财务风险: <span class="risk-category-percentage">35%</span></p>
                            <p>市场风险: <span class="risk-category-percentage">28%</span></p>
                            <p>管理风险: <span class="risk-category-percentage">22%</span></p>
                            <p>外部风险: <span class="risk-category-percentage">15%</span></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <i class="fas fa-filter"></i> 数据筛选
                </div>
                <div class="card-content">
                    <div class="form-group">
                        <label for="minRiskScore">最小风险评分</label>
                        <input type="number" id="minRiskScore" min="0" max="100" value="50">
                    </div>
                    <div class="form-group">
                        <label for="maxRiskScore">最大风险评分</label>
                        <input type="number" id="maxRiskScore" min="0" max="100" value="80">
                    </div>
                    <div class="form-group">
                        <label for="companySize">企业规模</label>
                        <select id="companySize">
                            <option value="all" selected>所有规模</option>
                            <option value="small">小型企业</option>
                            <option value="medium">中型企业</option>
                            <option value="large">大型企业</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>&nbsp;</label>
                        <button class="btn" id="applyFiltersBtn">
                            <i class="fas fa-filter"></i> 应用筛选
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 提供的人名列表
        const chineseNames = [
            '靳帆', '李洁', '王桂芳', '刘丽华', '蒋丽华', '张淑珍', '赵坤', '邱瑞', '杜春梅', '陈婷婷',
            '董桂荣', '段帅', '王斌', '林想', '张淑珍', '王斌', '高建国', '郑峰', '徐玉珍', '刘玉华',
            '许林', '韩华', '任秀珍', '周桂英', '张鑫', '刘强', '王斌', '张玲', '刘志强', '洪秀英',
            '李秀华', '陈淑珍', '牟桂英', '鞠辉', '龙萍', '尚英', '崔萍', '张秀荣', '陆志强', '李兵',
            '杜瑞', '赵丽丽', '王军', '魏志强', '程琳'
        ];

        // 模拟用户行为数据
        const userActivityData = chineseNames.map((name, index) => {
            const roles = ['管理员', '分析师', '普通用户'];
            const role = roles[Math.floor(Math.random() * roles.length)];
            const assessmentCount = Math.floor(Math.random() * 200) + 20; // 评估次数
            const averageScore = Math.floor(Math.random() * 30) + 50; // 平均评分 50-80
            const lastLogin = generateRandomPastDate(30); // 最近30天内的随机登录时间

            return {
                name: name,
                role: role,
                assessmentCount: assessmentCount,
                averageScore: averageScore,
                lastLogin: lastLogin
            };
        });

        let currentUserActivityPage = 1;
        const usersPerPage = 8; // 每页显示8个用户

        // 生成随机的过去日期字符串
        function generateRandomPastDate(days) {
            const date = new Date();
            date.setDate(date.getDate() - Math.floor(Math.random() * days));
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }


        // 模拟数据函数
        function generateRandomData(min, max, count) {
            return Array.from({length: count}, () => Math.floor(Math.random() * (max - min + 1)) + min);
        }

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            // 隐藏加载屏幕
            setTimeout(function() {
                document.getElementById('loadingOverlay').style.display = 'none';
            }, 1500);

            // 初始化图表
            initCharts();

            // 设置当前时间
            updateDateTime();

            // 渲染用户行为表格 (带分页)
            renderUserActivityTable(currentUserActivityPage);

            // 添加事件监听器
            setupEventListeners();

            // 模拟实时数据更新
            startRealTimeUpdates();
        });

        // 初始化所有图表
        function initCharts() {
            // 风险评估趋势图
            const assessmentTrendCtx = document.getElementById('assessmentTrendChart').getContext('2d');
            window.assessmentTrendChart = new Chart(assessmentTrendCtx, {
                type: 'line',
                data: {
                    labels: generateDateLabels(15),
                    datasets: [
                        {
                            label: '评估次数',
                            data: generateRandomData(20, 60, 15),
                            borderColor: '#00ccff',
                            backgroundColor: 'rgba(0, 204, 255, 0.1)',
                            tension: 0.4,
                            fill: true
                        },
                        {
                            label: '平均风险评分',
                            data: generateRandomData(50, 80, 15),
                            borderColor: '#ff3366',
                            backgroundColor: 'rgba(255, 51, 102, 0.1)',
                            tension: 0.4,
                            fill: true
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: false
                        }
                    },
                    plugins: {
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });

            // 风险分布图
            const riskDistributionCtx = document.getElementById('riskDistributionChart').getContext('2d');
            window.riskDistributionChart = new Chart(riskDistributionCtx, {
                type: 'pie',
                data: {
                    labels: ['低风险', '中风险', '高风险'],
                    datasets: [{
                        data: generateRandomData(100, 500, 3),
                        backgroundColor: [
                            '#33cc33',
                            '#ffcc00',
                            '#ff3366'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right'
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });

            // 用户活动图
            const userActivityCtx = document.getElementById('userActivityChart').getContext('2d');
            window.userActivityChart = new Chart(userActivityCtx, {
                type: 'bar',
                data: {
                    labels: ['管理员', '分析师', '普通用户'],
                    datasets: [
                        {
                            label: '评估次数',
                            data: generateRandomData(100, 300, 3),
                            backgroundColor: 'rgba(0, 204, 255, 0.7)'
                        },
                        {
                            label: '平均评分',
                            data: generateRandomData(50, 80, 3),
                            backgroundColor: 'rgba(255, 51, 102, 0.7)'
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top'
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });

            // 风险热力图
            window.riskHeatmap = echarts.init(document.getElementById('riskHeatmap'));
            updateHeatmap();

            // 风险预测图
            const riskPredictionCtx = document.getElementById('riskPredictionChart').getContext('2d');
            window.riskPredictionChart = new Chart(riskPredictionCtx, {
                type: 'line',
                data: {
                    labels: generateDateLabels(13, 'M/D'),
                    datasets: [
                        {
                            label: '实际风险评分',
                            data: [...generateRandomData(55, 70, 8), ...Array(5).fill(null)],
                            borderColor: '#00ccff',
                            backgroundColor: 'rgba(0, 204, 255, 0.1)',
                            tension: 0.4,
                            fill: false
                        },
                        {
                            label: '预测风险评分',
                            data: [...Array(8).fill(null), ...generateRandomData(60, 80, 5)],
                            borderColor: '#ffcc00',
                            backgroundColor: 'rgba(255, 204, 0, 0.1)',
                            tension: 0.4,
                            fill: false
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: false,
                            min: 55,
                            max: 85
                        }
                    },
                    plugins: {
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    },
                    animation: {
                        duration: 1000,
                        easing: 'easeOutQuart'
                    }
                }
            });
        }

        // 更新热力图数据
        function updateHeatmap() {
            const heatmapData = [];
            const cities = ['北京', '上海', '广州', '深圳', '成都', '武汉', '西安', '杭州', '南京', '天津'];
            const riskLevels = ['低风险', '中风险', '高风险'];

            for (let i = 0; i < cities.length; i++) {
                for (let j = 0; j < riskLevels.length; j++) {
                    const value = Math.floor(Math.random() * 100);
                    heatmapData.push([i, j, value]);
                }
            }

            const heatmapOption = {
                tooltip: {
                    position: 'top',
                    formatter: function (params) {
                        return params.name + ': ' + params.value[2] + '%';
                    }
                },
                grid: {
                    top: '10%',
                    bottom: '15%',
                    left: '5%',
                    right: '5%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: cities,
                    splitArea: {
                        show: true
                    }
                },
                yAxis: {
                    type: 'category',
                    data: riskLevels,
                    splitArea: {
                        show: true
                    }
                },
                visualMap: {
                    min: 0,
                    max: 100,
                    calculable: true,
                    orient: 'horizontal',
                    left: 'center',
                    bottom: '0%',
                    inRange: {
                        color: ['#33cc33', '#ffcc00', '#ff3366']
                    }
                },
                series: [{
                    name: '风险热力图',
                    type: 'heatmap',
                    data: heatmapData,
                    label: {
                        show: true,
                        formatter: function(params) {
                            return params.value[2] + '%';
                        }
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };

            window.riskHeatmap.setOption(heatmapOption);
            window.riskHeatmap.resize();
        }

        // 生成日期标签
        function generateDateLabels(count, format = 'M/D') {
            const labels = [];
            const today = new Date();

            for (let i = count - 1; i >= 0; i--) {
                const date = new Date();
                date.setDate(today.getDate() - i);
                const day = date.getDate();
                const month = date.getMonth() + 1;

                if (format === 'M/D') {
                    labels.push(`${month}/${day}`);
                } else {
                    labels.push(`${month}/${day}`);
                }
            }

            return labels;
        }

        // 设置当前时间
        function updateDateTime() {
            const userCard = document.querySelector('.sidebar .card-content p:nth-child(2)');
            const now = new Date();
            const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
            userCard.innerHTML = `登录时间: ${formattedDate}`;

            // 每分钟更新一次
            setTimeout(updateDateTime, 60000);
        }

        // 渲染用户行为表格 (带分页)
        function renderUserActivityTable(page = 1) {
            const tableBody = document.getElementById('userActivityTableBody');
            tableBody.innerHTML = '';

            const startIndex = (page - 1) * usersPerPage;
            const endIndex = Math.min(startIndex + usersPerPage, userActivityData.length);
            const currentPageUsers = userActivityData.slice(startIndex, endIndex);

            currentPageUsers.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${user.name}</td>
                    <td>${user.role}</td>
                    <td>${user.assessmentCount}</td>
                    <td>${user.averageScore}</td>
                    <td>${user.lastLogin}</td>
                    <td><button class="btn detail-btn" style="padding: 5px 10px; font-size: 12px;">详情</button></td>
                `;
                tableBody.appendChild(row);
            });

            // 渲染分页按钮
            renderUserActivityPagination();

            // 添加用户详情按钮事件监听
            document.querySelectorAll('#userActivityTableBody .detail-btn').forEach(button => {
                button.addEventListener('click', function() {
                    const row = this.closest('tr');
                    const username = row.cells[0].textContent;
                    const role = row.cells[1].textContent;

                    alert(`用户详情：\n用户名: ${username}\n角色: ${role}`);
                });
            });
        }

        // 渲染用户行为表格分页按钮
        function renderUserActivityPagination() {
            const paginationContainer = document.getElementById('userActivityPagination');
            paginationContainer.innerHTML = '';

            const totalPages = Math.ceil(userActivityData.length / usersPerPage);

            // 上一页按钮
            const prevButton = document.createElement('button');
            prevButton.innerHTML = '<i class="fas fa-angle-left"></i>';
            prevButton.onclick = function() {
                if (currentUserActivityPage > 1) {
                    currentUserActivityPage--;
                    renderUserActivityTable(currentUserActivityPage);
                }
            };
            paginationContainer.appendChild(prevButton);

            // 页码按钮
            for (let i = 1; i <= totalPages; i++) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                if (i === currentUserActivityPage) {
                    pageButton.classList.add('active');
                }
                pageButton.onclick = function() {
                    currentUserActivityPage = i;
                    renderUserActivityTable(currentUserActivityPage);
                };
                paginationContainer.appendChild(pageButton);
            }

            // 下一页按钮
            const nextButton = document.createElement('button');
            nextButton.innerHTML = '<i class="fas fa-angle-right"></i>';
            nextButton.onclick = function() {
                if (currentUserActivityPage < totalPages) {
                    currentUserActivityPage++;
                    renderUserActivityTable(currentUserActivityPage);
                }
            };
            paginationContainer.appendChild(nextButton);
        }


        // 设置事件监听器
        function setupEventListeners() {
            // 刷新按钮事件
            document.getElementById('refreshDataBtn').addEventListener('click', function() {
                this.classList.add('fa-spin');
                this.disabled = true;

                setTimeout(function() {
                    updateAllCharts();

                    // 更新最后更新时间
                    updateLastUpdatedTimes();

                    document.getElementById('refreshDataBtn').classList.remove('fa-spin');
                    document.getElementById('refreshDataBtn').disabled = false;
                }, 1000);
            });

            // 侧边栏导航事件
            document.getElementById('riskConfigNav').addEventListener('click', function() {
                // 实际应用中这里会进行页面跳转
                alert('跳转到风险参数配置页面');
            });

            document.getElementById('userManagerNav').addEventListener('click', function() {
                 // 实际应用中这里会进行页面跳转
                alert('跳转到用户管理页面');
            });

            // 应用筛选按钮事件
            document.getElementById('applyFiltersBtn').addEventListener('click', function() {
                const minScore = parseInt(document.getElementById('minRiskScore').value);
                const maxScore = parseInt(document.getElementById('maxRiskScore').value);
                const companySize = document.getElementById('companySize').value;

                if (isNaN(minScore) || isNaN(maxScore) || minScore > maxScore) {
                    alert('请输入有效的分数范围');
                    return;
                }

                alert(`已应用筛选条件：\n最小风险评分: ${minScore}\n最大风险评分: ${maxScore}\n企业规模: ${companySize}`);

                // 这里可以添加实际的筛选逻辑，并更新图表和表格
                // 例如：根据筛选条件过滤 userActivityData，然后重新渲染表格 (需要重新实现 renderUserActivityTable 以支持筛选)
            });

            // 日期范围、风险类型、行业筛选变化事件
            document.getElementById('dateRange').addEventListener('change', updateAllCharts);
            document.getElementById('riskType').addEventListener('change', updateAllCharts);
            document.getElementById('industry').addEventListener('change', updateAllCharts);
        }

        // 更新所有图表
        function updateAllCharts() {
            // 更新风险评估趋势图
            window.assessmentTrendChart.data.labels = generateDateLabels(15); // 根据日期范围更新标签
            window.assessmentTrendChart.data.datasets[0].data = generateRandomData(20, 60, 15);
            window.assessmentTrendChart.data.datasets[1].data = generateRandomData(50, 80, 15);
            window.assessmentTrendChart.update();

            // 更新风险分布图
            window.riskDistributionChart.data.datasets[0].data = generateRandomData(100, 500, 3);
            window.riskDistributionChart.update();

            // 更新用户活动图
            // 这里的用户活动图数据是基于模拟的 userActivityData，可以根据需要调整
            window.userActivityChart.data.datasets[0].data = generateRandomData(100, 300, 3);
            window.userActivityChart.data.datasets[1].data = generateRandomData(50, 80, 3);
            window.userActivityChart.update();

            // 更新热力图
            updateHeatmap();

            // 更新风险预测图
            const actualData = [...generateRandomData(55, 70, 8), ...Array(5).fill(null)];
            const predictedData = [...Array(8).fill(null), ...generateRandomData(60, 80, 5)];
            window.riskPredictionChart.data.datasets[0].data = actualData;
            window.riskPredictionChart.data.datasets[1].data = predictedData;
            window.riskPredictionChart.update();

            // 更新行业和风险类别百分比
            updateIndustryPercentages();
            updateRiskCategoryPercentages();
        }

        // 更新最后更新时间
        function updateLastUpdatedTimes() {
            const now = new Date();
            const timeString = now.toLocaleTimeString();

            document.getElementById('trendLastUpdated').textContent = `最后更新: ${timeString}`;
            document.getElementById('distributionLastUpdated').textContent = `最后更新: ${timeString}`;
            document.getElementById('activityLastUpdated').textContent = `最后更新: ${timeString}`;
            document.getElementById('heatmapLastUpdated').textContent = `最后更新: ${timeString}`;
            document.getElementById('predictionLastUpdated').textContent = `最后更新: ${timeString}`;
        }

        // 更新行业百分比
        function updateIndustryPercentages() {
            const percentages = generateRandomData(10, 30, 4);
            let total = percentages.reduce((sum, value) => sum + value, 0);
            const normalized = percentages.map(value => Math.round(value / total * 100));

            document.querySelectorAll('.industry-percentage').forEach((element, index) => {
                element.textContent = `${normalized[index]}%`;
            });
        }

        // 更新风险类别百分比
        function updateRiskCategoryPercentages() {
            const percentages = generateRandomData(10, 35, 4);
            let total = percentages.reduce((sum, value) => sum + value, 0);
            const normalized = percentages.map(value => Math.round(value / total * 100));

            document.querySelectorAll('.risk-category-percentage').forEach((element, index) => {
                element.textContent = `${normalized[index]}%`;
            });
        }

        // 模拟实时数据更新
        function startRealTimeUpdates() {
            setInterval(function() {
                // 随机更新一些数据
                if (Math.random() > 0.7) {
                    // 随机更新用户行为表格中的最后登录时间
                    const userRows = document.querySelectorAll('#userActivityTableBody tr');
                    if (userRows.length > 0) {
                        const randomRow = userRows[Math.floor(Math.random() * userRows.length)];
                        const newLoginTime = new Date();
                        newLoginTime.setMinutes(newLoginTime.getMinutes() - Math.floor(Math.random() * 60));
                        randomRow.cells[4].textContent = newLoginTime.toLocaleString();
                    }
                }

                // 随机更新系统状态
                if (Math.random() > 0.95) {
                    const statusElement = document.getElementById('systemStatus');
                    statusElement.textContent = Math.random() > 0.5 ? '正常运行' : '维护中';
                    statusElement.className = 'status-badge ' + (statusElement.textContent === '正常运行' ? 'status-active' : 'status-inactive');
                }

                // 随机更新统计数字
                if (Math.random() > 0.8) {
                    const assessmentsElement = document.querySelector('.total-assessments');
                    const currentAssessments = parseInt(assessmentsElement.textContent.replace(/,/g, ''));
                    assessmentsElement.textContent = (currentAssessments + Math.floor(Math.random() * 10)).toLocaleString();

                    const highRiskElement = document.querySelector('.high-risk-companies');
                    const currentHighRisk = parseInt(highRiskElement.textContent);
                    highRiskElement.textContent = currentHighRisk + Math.floor(Math.random() * 3) - 1;

                    const todayAssessmentsElement = document.querySelector('.today-assessments');
                    const currentTodayAssessments = parseInt(todayAssessmentsElement.textContent);
                    todayAssessmentsElement.textContent = currentTodayAssessments + Math.floor(Math.random() * 2);
                }
            }, 30000); // 每30秒模拟一次数据变化
        }
    </script>
</body>
</html>